<template>
  <van-cell-group>
    <van-cell
        title="头像"
        is-link
        label="点击以更改头像"
        @click="avatarDialogVisible = true"
    >
      <van-image
          round
          width="2rem"
          height="2rem"
          position="top "
          :src="imgUrl"
      />
    </van-cell>
    <van-cell
        :title="item.label"
        :value="item.data"
        v-for="item in table"
        :key="item.index"
        :label="item.des"
    />
    <van-cell
        title="密码"
        is-link
        label="点击以修改密码"
        @click="passwordUpdateVisible = true"
    />
    <van-button type="primary" block @click="phoneUpdateVisible = true"
    >修改手机号
    </van-button>
    <van-button type="danger" block @click="logout">退出登录</van-button>
  </van-cell-group>
  <van-dialog
      v-model:show="avatarDialogVisible"
      title="更新头像"
      show-cancel-button
      @confirm="uploadAvatar"
      closeOnClickOverlay="true"
      :beforeClose="beforeClose"
      @cancel="avatarDialogVisible = false"
  >
    <van-uploader v-model="fileList" multiple/>
  </van-dialog>
  <van-dialog
      v-model:show="passwordUpdateVisible"
      title="修改密码"
      show-cancel-button
      @confirm="updatePassword(form)"
      closeOnClickOverlay="true"
      :beforeClose="beforeClose"
      @cancel="passwordUpdateVisible = false"
  >
    <van-form ref="form">
      <van-cell-group inset>
        <van-field
            v-model="form.password"
            type="password"
            name="新密码"
            label="新密码"
            placeholder="新密码"
            :rules="rules.password"
        />
        <van-field
            v-model="form.aPassword"
            type="password"
            name="确认密码"
            label="确认密码"
            placeholder="确认密码"
            :rules="rules.aPassword"
        />
      </van-cell-group>
    </van-form>
  </van-dialog>
  <van-dialog
      v-model:show="phoneUpdateVisible"
      title="修改手机号"
      show-cancel-button
      @confirm="updatePhone(formPhone)"
      closeOnClickOverlay="true"
      :beforeClose="beforeClose"
      @cancel="phoneUpdateVisible = false"
  >
    <van-form ref="form">
      <van-cell-group inset>
        <van-field
            v-model="formPhone.phone"
            name="新手机号"
            label="新手机号"
            placeholder="新手机号"
            :rules="rules.phone"
        />
      </van-cell-group>
    </van-form>
  </van-dialog>
</template>

<script>
import {
  downloadAvatar,
  updateCurrentUser,
  uploadAvatar,
  lookCurrentUser,
} from "../api/user";
import {showToast, showConfirmDialog} from "vant";

export default {
  data() {
    return {
      imgUrl: "",
      avatarDialogVisible: false,
      passwordUpdateVisible: false,
      phoneUpdateVisible: false,
      currentUser: {},
      form: {
        password: "",
      },
      formPhone: {
        phone: "",
      },
      srcList: [],
      fileList: [],
      table: [
        {
          index: 1,
          label: "ID",
          name: "id",
          des: "用户唯一标识",
          data: "",
        },
        {
          index: 2,
          label: "姓名",
          name: "name",
          des: "您登录所使用的账户名",
          data: "",
        },
        {
          index: 3,
          label: "创建时间",
          name: "createTime",
          des: "第一次创建的时间",
          data: "",
        },
        {
          index: 4,
          label: "手机号",
          name: "phone",
          des: "您当前可用的手机号",
          data: "",
        },
        {
          index: 5,
          label: "联系地址",
          name: "addressInfo",
          des: "当前所在地址,如为空,请联系管理员进行修改!",
          data: "",
        },
      ],
      rules: {
        userName: [{required: true, message: "用户名不得为空!"}],
        password: [
          {required: true, message: "密码不得为空!"},
          {
            required: true,
            validator: (val) => {
              if (val.length < 6 || val.length > 12) {
                return "密码长度介于6~12位之间";
              }
            },
          },
        ],
        aPassword: [
          {required: true, message: "第二次密码不得为空!"},
          {
            required: true,
            validator: (value) => {
              if (value !== this.form.password) {
                return "两次输入密码不一致!";
              }
            },
          },
        ],
        phone: [
          {required: true, message: "手机号不得为空!"},
          {
            required: true,
            validator: (value) => {
              if (
                  !/^(((13[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(17[3-8]{1})|(18[0-9]{1})|(19[0-9]{1})|(14[5-7]{1}))+\d{8})$/.test(
                      value
                  )
              ) {
                return "请输入正确的手机号!";
              }
            },
          },
        ],
      },
    };
  },
  created() {
    this.downloadAvatar();
    this.lookCurrentUser(sessionStorage.getItem("user"));
  },
  methods: {
    //下载头像
    downloadAvatar() {
      var id = sessionStorage.getItem("user");
      downloadAvatar(id).then((req) => {
        if (req.data === 0) {
          return;
        }
        let blob = new Blob([req.data], {type: "image/jpeg"});
        const imageUrl = URL.createObjectURL(blob);
        this.imgUrl = imageUrl;
        this.srcList.push(imageUrl);
      });
    },
    //头像上传
    uploadAvatar() {
      console.log(this.fileList[0]);
      if (this.fileList.length === 0) {
        showToast("请上传图片!");
        return;
      }
      var param = new FormData();
      this.fileList.forEach((val, index) => {
        param.append("file", val.file);
      });
      var id = sessionStorage.getItem("user");
      uploadAvatar(param, id).then((req) => {
        if (req.data.success) {
          this.avatarDialogVisible = false;
          showToast("修改成功!");
          this.downloadAvatar();
        } else {
          showToast("修改失败!");
        }
      });
    },
    //退出登录
    logout() {
      showConfirmDialog({
        title: "退出登录",
        message: "退出登录后需要重新登录,是否继续?",
        theme: "round-button",
      }).then(() => {
        sessionStorage.clear();
        this.$router.push({name: "login"});
      });
    },
    //查看当前用户
    lookCurrentUser(id) {
      lookCurrentUser(id).then((req) => {
        this.currentUser = req.data.data;
        for (var i = 0; i < this.table.length; i++) {
          this.table[i].data = this.currentUser[this.table[i].name];
        }
      });
    },
    //修改密码
    updatePassword(user) {
      this.$refs.form
          .validate()
          .then(() => {
            user.id = sessionStorage.getItem("user");
            updateCurrentUser(user).then((req) => {
              if (req.data.success) {
                this.passwordDialogVisible = false;
                showToast("修改成功!请重新登录!");
                sessionStorage.clear();
                this.$router.push({name: "login"});
              } else {
                showToast("修改失败!");
              }
            });
          })
          .catch(() => {
            return false;
          });
    },
    //修改手机号
    updatePhone(user) {
      this.$refs.form
          .validate()
          .then(() => {
            user.id = sessionStorage.getItem("user");
            updateCurrentUser(user).then((req) => {
              if (req.data.success) {
                this.phoneUpdateVisible = false;
                showToast("修改成功!");
                this.lookCurrentUser(sessionStorage.getItem("user"));
              } else {
                showToast("修改失败!");
              }
            });
          })
          .catch(() => {
            return false;
          });
    },
    beforeClose(action) {
      new Promise((resolve) => {
        if (action === "confirm") {
          resolve(true);
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
</style>